import {Component, OnInit, Input} from '@angular/core';
import {ApiService} from "@core/services/http/api.service";
import {GridConfigService} from 'app/core/config/grid-config.service';
import {GridOptions} from '@ag-grid-community/core';
import {ActivatedRoute}  from "@angular/router";
import {ApesMessageService} from "@shared/apes/message";
import {UserAuthService} from "@core/services/user-auth.service";
import { BiService } from '../../bi.service';

@Component({
  selector: 'apes-apes-keep-insurance-order',
  templateUrl: './apes-keep-insurance-order.component.html',
  styleUrls: ['apes-keep-insurance-order.component.scss']
})
export class ApesKeepInsuranceOrderComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [{hide: true, style: 'default', label: '查询', id: 'action_query',loading: false},
    {hide: true, style: 'default', label: '展开查询条件', id: 'action_show'},
    // {hide: false, style: 'default', label: '重置查询条件', id: 'action_reset'}
  ];
  title = '';
  ctx = {model: {}};

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  hidn: any = "none";
  height: any = window.innerHeight - 220 + 'px';

  // 饼图相关
  salesPieData: any;
  xinbao = [];
  xubao = [];
  xin : any;
  xu : any;

  pieData: any;
  yixubao = [];
  yiguoqi = [];
  yxb : any;
  ygq : any;

  sevenData: any[];    // 柱型图相关

  mdjcTime: any[] = [];
  mdjcTime_ks = null;
  mdjcTime_js = null;

  endDate = null;      // 默认结束时间
  startDate = null;    // 默认开始时间 当天的前7天
  nowDay: any;

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData: any;
  companyList: any[];

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private routerInfo: ActivatedRoute,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private bi: BiService) {
    this.columnDefs = [
      {headerName: "日期", field: 'RQ'},
      {headerName: "销售单数", field: 'XSDS'},
      {headerName: "销售金额", field: 'XSZJE'},
      {headerName: "应续保数", field: 'YXB'},
      {headerName: "应续保金额", field: 'YXBJE'},
      {headerName: "已续保数", field: 'XU'},
      {headerName: "已续保金额", field: 'XUBJE'},
      {headerName: "新保单数", field: 'XIN'},
      {headerName: "新保金额", field: 'XINBJE'},
      {headerName: "续保率", field: 'XBL'}
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 20,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 当月 数据
    this.endDate = new Date();
    this.nowDay = this.endDate.toISOString().slice(8, 10);
    this.startDate = new Date(this.endDate.getTime() - ((this.nowDay - 1 ) * 24 * 60 * 60 * 1000));
    this.mdjcTime.push(this.startDate);
    this.mdjcTime.push(this.endDate);
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => { this.companyData = value });
    this.submit();

  }

  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.submit();
        this.hidn = "none";
      } else if (data.id === 'action_reset') {
        this.action_reset();
      } else if (data.id === 'action_show') {
        this.action_show();
      }
    }
  }

  action_reset() {
  }

  action_show() {
    if (this.hidn === "none") {
      this.hidn = "flex";
    } else if (this.hidn === "flex") {
      this.hidn = "none";
    }
  }

  submit() {
    // if(this.companyList.length <= 0){
    //   this.companyList.push(this.companyId);
    // }
    this.rowData = [];
    this.xinbao = [];
    this.xubao = [];
    this.xin = 0;
    this.xu = 0;
    this.yixubao = [];
    this.yiguoqi = [];
    this.yxb = 0;
    this.ygq = 0;
    // 传的时间 进行转换

    if(this.mdjcTime.length > 0) {
      this.getDate(this.mdjcTime, "mdjcTime_ks", "mdjcTime_js");
      this.getTablesData();
    }else {
      this.msg.error('日期必填，不能为空！');
      this.buttonBar[0].loading = false;
    }
    this.buttonBar[0].loading = false;
  }

  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  getTablesData() {
    let data = { 'interfaceMethod': 'ipmBusinessStatementService.getXbfx', 'pdata': {
      'ZDRQ_SJ': this.mdjcTime_ks, 'SKRQ_SJ': this.mdjcTime_js, 'companyId': this.companyList } };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.rowData = data;
            data = data.sort(this.sortarr('RQ'));

            for (let i = 0, len = data.length; i < len; i++) {
              this.xinbao.push(data[i].XIN);
              this.xubao.push(data[i].XU);
              this.yixubao.push(data[i].XU);
              this.yiguoqi.push(data[i].YGQ);
            }
            // 饼图 新保数据获取
            for (let i = 0, len = this.xinbao.length; i < len; i++) {
              this.xin += this.xinbao[i];
            }
            for (let i = 0, len = this.xubao.length; i < len; i++) {
              this.xu += this.xubao[i];
            }
            for (let i = 0, len = this.yixubao.length; i < len; i++) {
              this.yxb += this.yixubao[i];
            }
            for (let i = 0, len = this.yiguoqi.length; i < len; i++) {
              this.ygq += this.yiguoqi[i];
            }
            //柱型图 数据获取
            const sevenList = data.slice(0, data.length);
            this.sevenData = sevenList.map((value) => {
              return { x: value['RQ'], y: value['XU'] };
            });
            // 加载 饼图
            this.salesPieData = this.getSalesTypePie();
            this.pieData = this.getTypePie();
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 饼图
  getSalesTypePie() {
    return [
      { x: '新保数', y: this.xin },
      { x: '续保数', y: this.xu },
    ];
  }
  getTypePie() {
    return [
      { x: '已续保', y: this.yxb },
      { x: '已过期', y: this.ygq },
    ];
  }

  // 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return a[key] - b[key];
    };
  }
}
